<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所在区域" prop="location">
        <el-select v-model="queryParams.location" placeholder="请选择所在区域">
          <el-option v-for="dict in dict.type.location" :key="dict.value" :label="dict.label" :value="dict.value"
            @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="具体分类" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择具体分类">
          <el-option v-for="dict in dict.type.types" :key="dict.value" :label="dict.label" :value="dict.value"
            @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['web:home:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['web:home:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['web:home:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['web:home:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column label="归属页面" align="center" prop="pageId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.page_num" :value="scope.row.pageId" />
        </template>
      </el-table-column>
      <el-table-column label="资源种类" align="center" prop="resourceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.resource_type" :value="scope.row.resourceType" />
        </template>
      </el-table-column>
      <el-table-column label="所在区域" align="center" prop="location">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.location" :value="scope.row.location" />
        </template>
      </el-table-column>
      <el-table-column label="具体分类" align="center" prop="typeId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.types" :value="scope.row.typeId" />
        </template>
      </el-table-column>
      <el-table-column label="主导航" align="center" prop="nav">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nav" :value="scope.row.nav" />
        </template>
      </el-table-column>
      <el-table-column label="子导航" align="center" prop="childNav">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nav" :value="scope.row.childNav" />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['web:home:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['web:home:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改首页模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="归属页面" prop="pageId">
          <el-select v-model="form.pageId" placeholder="请选择归属页面">
            <el-option v-for="dict in dict.type.page_num" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源种类" prop="resourceType">
          <el-select v-model="form.resourceType" placeholder="请选择资源种类">
            <el-option v-for="dict in dict.type.resource_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在区域" prop="location">
          <el-select v-model="form.location" placeholder="请选择所在区域">
            <el-option v-for="dict in dict.type.location" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体分类" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择具体分类">
            <el-option v-for="dict in dict.type.types" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="页面内容" prop="content">
          <el-input type="textarea" v-model="form.content"></el-input>
        </el-form-item>
            <!-- 上传组件 -->
            <el-form-item label="上传" prop="url">
          <el-upload class="upload-demo" :headers="upload.headers" :action="upload.url" :on-preview="handlePreview"
            :on-remove="handleRemove" :before-remove="beforeRemove" :on-success="handleSuccess" :on-error="handleError"
            :on-exceed="handleExceed" :file-list="fileList" :limit="1" list-type="text" accept="image/*,video/*">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              支持上传jpg/png图片或mp4/mov视频文件，且不超过100MB
            </div>
          </el-upload>
        </el-form-item>
        <!-- 预览对话框 -->
        <el-dialog :visible.sync="previewVisible" :modal="false" width="80%" top="5vh" :title="previewTitle">
          <!-- 图片预览 -->
          <img v-if="previewType === 'image'" :src="previewUrl"
            style="width: 100%; max-height: 70vh; object-fit: contain;" alt="预览图片" />
          <!-- 视频预览 -->
          <video v-else-if="previewType === 'video'" :src="previewUrl" controls style="width: 100%; max-height: 70vh;">
            您的浏览器不支持视频播放
          </video>
          <span slot="footer" class="dialog-footer">
            <el-button @click="previewVisible = false">关闭</el-button>
          </span>
        </el-dialog>
        <el-form-item label="导航" prop="nav">
          <el-select v-model="form.nav" placeholder="请选择是否导航">
            <el-option v-for="dict in dict.type.nav" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="子导航" prop="childNav">
          <el-select v-model="form.childNav" placeholder="请选择是否是子导航">
            <el-option v-for="dict in dict.type.nav" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHome, getHome, delHome, addHome, updateHome } from "@/api/web/home"
import { getToken } from '@/utils/auth'
export default {
  name: "Home",
  dicts: ['resource_type', 'types', 'nav', 'location', 'page_num'],
  data() {
    return {
       // 图片预览相关
       previewVisible: false, // 预览对话框显示状态
      previewUrl: "", // 预览的URL
      previewType: "", // 预览类型：image或video
      previewTitle: "", // 预览对话框标题
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      //图片上传
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网页数据表格数据
      homeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        resourceType: null,
        location: null,
        typeId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 自定义编号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
   /** 初始化文件列表，用于回显 */
   initFileList(url) {
      if (url) {
        // 从URL中提取文件名
        const fileName = url.substring(url.lastIndexOf("/") + 1);
        this.fileList = [
          {
            name: fileName,
            url: url,
          },
        ];
      } else {
        this.fileList = [];
      }
    },

    /** 上传成功处理 */
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 将服务器返回的URL保存到表单
        this.form.url = response.url;
        // 更新文件列表用于回显
        this.fileList = [
          {
            name: file.name,
            url: response.url,
          },
        ];
        this.$message.success("上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },

    /** 上传失败处理 */
    handleError(err, file, fileList) {
      this.$message.error("上传失败: " + (err.message || "未知错误"));
    },

    /** 文件预览 */
    handlePreview(file) {
      // 判断文件类型
      const fileName = file.name.toLowerCase();
      const isImage = fileName.endsWith(".jpg") ||
        fileName.endsWith(".jpeg") ||
        fileName.endsWith(".png") ||
        fileName.endsWith(".gif");
      const isVideo = fileName.endsWith(".mp4") ||
        fileName.endsWith(".mov") ||
        fileName.endsWith(".avi");

      if (isImage) {
        this.previewType = "image";
        this.previewTitle = "图片预览";
      } else if (isVideo) {
        this.previewType = "video";
        this.previewTitle = "视频预览";
      } else {
        this.$message.warning("不支持预览此文件类型");
        return;
      }
      // 设置预览URL
      this.previewUrl = file.url;
      this.previewVisible = true;
    },

    /** 文件移除 */
    handleRemove(file, fileList) {
      // 移除文件时清空表单URL
      this.form.url = "";
      this.fileList = [];
    },

    /** 移除前确认 */
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    },

    /** 超出限制处理 */
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${fileList.length} 个文件`);
    },
    /** 查询网页数据列表 */
    getList() {
      this.loading = true
      listHome(this.queryParams).then(response => {
        this.homeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        resourceType: null,
        location: null,
        typeId: null,
        url: null,
        nav: null,
        sort: null,
        childNav: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.fileList = [];
      this.open = true
      this.title = "添加网页数据"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getHome(id).then(response => {
        this.form = response.data
        if (response.data.url) {
          this.initFileList(response.data.url);
        } else {
          this.fileList = [];
        }
        this.open = true
        this.title = "修改网页数据"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHome(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addHome(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除网页数据编号为"' + ids + '"的数据项？').then(function () {
        return delHome(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('web/home/export', {
        ...this.queryParams
      }, `home_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
